home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2002 November / CD 1 / APC0211D1.ISO / workshop / prog / files / ActivePerl-5.6.1.633-MSWin32.msi / _1fa13a5e4fac97e3730f828a08dbea2d < prev    next >
Encoding:
Text File  |  2002-05-01  |  12.5 KB  |  444 lines

  1. # $Id: Common.pm,v 1.19 2001/01/05 18:53:11 gisle Exp $
  2. #
  3. package HTTP::Request::Common;
  4.  
  5. use strict;
  6. use vars qw(@EXPORT @EXPORT_OK $VERSION $DYNAMIC_FILE_UPLOAD);
  7.  
  8. $DYNAMIC_FILE_UPLOAD ||= 0;  # make it defined (don't know why)
  9.  
  10. require Exporter;
  11. *import = \&Exporter::import;
  12. @EXPORT =qw(GET HEAD PUT POST);
  13. @EXPORT_OK = qw($DYNAMIC_FILE_UPLOAD);
  14.  
  15. require HTTP::Request;
  16. use Carp();
  17.  
  18. $VERSION = sprintf("%d.%02d", q$Revision: 1.19 $ =~ /(\d+)\.(\d+)/);
  19.  
  20. my $CRLF = "\015\012";   # "\r\n" is not portable
  21.  
  22. sub GET  { _simple_req('GET',  @_); }
  23. sub HEAD { _simple_req('HEAD', @_); }
  24. sub PUT  { _simple_req('PUT' , @_); }
  25.  
  26. sub POST
  27. {
  28.     my $url = shift;
  29.     my $req = HTTP::Request->new(POST => $url);
  30.     my $content;
  31.     $content = shift if @_ and ref $_[0];
  32.     my($k, $v);
  33.     while (($k,$v) = splice(@_, 0, 2)) {
  34.     if (lc($k) eq 'content') {
  35.         $content = $v;
  36.     } else {
  37.         $req->push_header($k, $v);
  38.     }
  39.     }
  40.     my $ct = $req->header('Content-Type');
  41.     unless ($ct) {
  42.     $ct = 'application/x-www-form-urlencoded';
  43.     } elsif ($ct eq 'form-data') {
  44.     $ct = 'multipart/form-data';
  45.     }
  46.  
  47.     if (ref $content) {
  48.     if ($ct =~ m,^multipart/form-data\s*(;|$),i) {
  49.         require HTTP::Headers::Util;
  50.         my @v = HTTP::Headers::Util::split_header_words($ct);
  51.         Carp::carp("Multiple Content-Type headers") if @v > 1;
  52.         @v = @{$v[0]};
  53.  
  54.         my $boundary;
  55.         my $boundary_index;
  56.         for (my @tmp = @v; @tmp;) {
  57.         my($k, $v) = splice(@tmp, 0, 2);
  58.         if (lc($k) eq "boundary") {
  59.             $boundary = $v;
  60.             $boundary_index = @v - @tmp - 1;
  61.             last;
  62.         }
  63.         }
  64.  
  65.         ($content, $boundary) = form_data($content, $boundary, $req);
  66.  
  67.         if ($boundary_index) {
  68.         $v[$boundary_index] = $boundary;
  69.         } else {
  70.         push(@v, boundary => $boundary);
  71.         }
  72.  
  73.         $ct = HTTP::Headers::Util::join_header_words(@v);
  74.     } else {
  75.         # We use a temporary URI object to format
  76.         # the application/x-www-form-urlencoded content.
  77.         require URI;
  78.         my $url = URI->new('http:');
  79.         $url->query_form(ref($content) eq "HASH" ? %$content : @$content);
  80.         $content = $url->query;
  81.     }
  82.     }
  83.  
  84.     $req->header('Content-Type' => $ct);  # might be redundant
  85.     if (defined($content)) {
  86.     $req->header('Content-Length' =>
  87.              length($content)) unless ref($content);
  88.     $req->content($content);
  89.     }
  90.     $req;
  91. }
  92.  
  93.  
  94. sub _simple_req
  95. {
  96.     my($method, $url) = splice(@_, 0, 2);
  97.     my $req = HTTP::Request->new($method => $url);
  98.     my($k, $v);
  99.     while (($k,$v) = splice(@_, 0, 2)) {
  100.     if (lc($k) eq 'content') {
  101.         $req->add_content($v);
  102.     } else {
  103.         $req->push_header($k, $v);
  104.     }
  105.     }
  106.     $req;
  107. }
  108.  
  109.  
  110. sub form_data   # RFC1867
  111. {
  112.     my($data, $boundary, $req) = @_;
  113.     my @data = ref($data) eq "HASH" ? %$data : @$data;  # copy
  114.     my $fhparts;
  115.     my @parts;
  116.     my($k,$v);
  117.     while (($k,$v) = splice(@data, 0, 2)) {
  118.     if (!ref($v)) {
  119.         $k =~ s/([\\\"])/\\$1/g;  # escape quotes and backslashes
  120.         push(@parts,
  121.          qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v));
  122.     } else {
  123.         my($file, $usename, @headers) = @$v;
  124.         unless (defined $usename) {
  125.         $usename = $file;
  126.         $usename =~ s,.*/,, if defined($usename);
  127.         }
  128.         my $disp = qq(form-data; name="$k");
  129.         $disp .= qq(; filename="$usename") if $usename;
  130.         my $content = "";
  131.         my $h = HTTP::Headers->new(@headers);
  132.         my $ct = $h->header("Content-Type");
  133.         if ($file) {
  134.         require Symbol;
  135.         my $fh = Symbol::gensym();
  136.         open($fh, $file) or Carp::croak("Can't open file $file: $!");
  137.         binmode($fh);
  138.         if ($DYNAMIC_FILE_UPLOAD) {
  139.             # will read file later
  140.             $content = $fh;
  141.         } else {
  142.             local($/) = undef; # slurp files
  143.             $content = <$fh>;
  144.             close($fh);
  145.             $h->header("Content-Length" => length($content));
  146.         }
  147.         unless ($ct) {
  148.             require LWP::MediaTypes;
  149.             $ct = LWP::MediaTypes::guess_media_type($file, $h);
  150.         }
  151.         }
  152.         if ($h->header("Content-Disposition")) {
  153.         # just to get it sorted first
  154.         $disp = $h->header("Content-Disposition");
  155.         $h->remove_header("Content-Disposition");
  156.         }
  157.         if ($h->header("Content")) {
  158.         $content = $h->header("Content");
  159.         $h->remove_header("Content");
  160.         }
  161.         my $head = join($CRLF, "Content-Disposition: $disp",
  162.                        $h->as_string($CRLF),
  163.                        "");
  164.         if (ref $content) {
  165.         push(@parts, [$head, $content]);
  166.         $fhparts++;
  167.         } else {
  168.         push(@parts, $head . $content);
  169.         }
  170.     }
  171.     }
  172.     return "" unless @parts;
  173.  
  174.     my $content;
  175.     if ($fhparts) {
  176.     $boundary = boundary(10) # hopefully enough randomness
  177.         unless $boundary;
  178.  
  179.     # add the boundaries to the @parts array
  180.     for (1..@parts-1) {
  181.         splice(@parts, $_*2-1, 0, "$CRLF--$boundary$CRLF");
  182.     }
  183.     unshift(@parts, "--$boundary$CRLF");
  184.     push(@parts, "$CRLF--$boundary--$CRLF");
  185.  
  186.     # See if we can generate Content-Length header
  187.     my $length = 0;
  188.     for (@parts) {
  189.         if (ref $_) {
  190.          my ($head, $f) = @$_;
  191.         my $file_size;
  192.         unless ( -f $f && ($file_size = -s _) ) {
  193.             # The file is either a dynamic file like /dev/audio
  194.             # or perhaps a file in the /proc file system where
  195.             # stat may return a 0 size even though reading it
  196.             # will produce data.  So we cannot make
  197.             # a Content-Length header.  
  198.             undef $length;
  199.             last;
  200.         }
  201.             $length += $file_size + length $head;
  202.         } else {
  203.         $length += length;
  204.         }
  205.         }
  206.         $length && $req->header('Content-Length' => $length);
  207.  
  208.     # set up a closure that will return content piecemeal
  209.     $content = sub {
  210.         for (;;) {
  211.         unless (@parts) {
  212.             defined $length && $length != 0 &&
  213.                 Carp::croak "length of data sent did not match calculated Content-Length header.  Probably because uploaded file changed in size during transfer.";
  214.             return;
  215.         }
  216.         my $p = shift @parts;
  217.         unless (ref $p) {
  218.             $p .= shift @parts while @parts && !ref($parts[0]);
  219.             defined $length && ($length -= length $p);
  220.             return $p;
  221.         }
  222.         my($buf, $fh) = @$p;
  223.         my $buflength = length $buf;
  224.         my $n = read($fh, $buf, 2048, $buflength);
  225.         if ($n) {
  226.             $buflength += $n;
  227.             unshift(@parts, ["", $fh]);
  228.         } else {
  229.             close($fh);
  230.         }
  231.         if ($buflength) {
  232.             defined $length && ($length -= $buflength);
  233.             return $buf 
  234.             }
  235.         }
  236.     };
  237.  
  238.     } else {
  239.     $boundary = boundary() unless $boundary;
  240.  
  241.     my $bno = 0;
  242.       CHECK_BOUNDARY:
  243.     {
  244.         for (@parts) {
  245.         if (index($_, $boundary) >= 0) {
  246.             # must have a better boundary
  247.             $boundary = boundary(++$bno);
  248.             redo CHECK_BOUNDARY;
  249.         }
  250.         }
  251.         last;
  252.     }
  253.     $content = "--$boundary$CRLF" .
  254.                join("$CRLF--$boundary$CRLF", @parts) .
  255.            "$CRLF--$boundary--$CRLF";
  256.     }
  257.  
  258.     wantarray ? ($content, $boundary) : $content;
  259. }
  260.  
  261.  
  262. sub boundary
  263. {
  264.     my $size = shift || return "xYzZY";
  265.     require MIME::Base64;
  266.     my $b = MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), "");
  267.     $b =~ s/[\W]/X/g;  # ensure alnum only
  268.     $b;
  269. }
  270.  
  271. 1;
  272.  
  273. __END__
  274.  
  275. =head1 NAME
  276.  
  277. HTTP::Request::Common - Construct common HTTP::Request objects
  278.  
  279. =head1 SYNOPSIS
  280.  
  281.   use HTTP::Request::Common;
  282.   $ua = LWP::UserAgent->new;
  283.   $ua->request(GET 'http://www.sn.no/');
  284.   $ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]);
  285.  
  286. =head1 DESCRIPTION
  287.  
  288. This module provide functions that return newly created HTTP::Request
  289. objects.  These functions are usually more convenient to use than the
  290. standard HTTP::Request constructor for these common requests.  The
  291. following functions are provided.
  292.  
  293. =over 4
  294.  
  295. =item GET $url, Header => Value,...
  296.  
  297. The GET() function returns a HTTP::Request object initialized with the
  298. GET method and the specified URL.  Without additional arguments it
  299. is exactly equivalent to the following call
  300.  
  301.   HTTP::Request->new(GET => $url)
  302.  
  303. but is less cluttered.  It also reads better when used together with the
  304. LWP::UserAgent->request() method:
  305.  
  306.   my $ua = new LWP::UserAgent;
  307.   my $res = $ua->request(GET 'http://www.sn.no')
  308.   if ($res->is_success) { ...
  309.  
  310. You can also initialize header values in the request by specifying
  311. some key/value pairs as optional arguments.  For instance:
  312.  
  313.   $ua->request(GET 'http://www.sn.no',
  314.                If_Match => 'foo',
  315.                    From     => 'gisle@aas.no',
  316.               );
  317.  
  318. A header key called 'Content' is special and when seen the value will
  319. initialize the content part of the request instead of setting a header.
  320.  
  321. =item HEAD $url, [Header => Value,...]
  322.  
  323. Like GET() but the method in the request is HEAD.
  324.  
  325. =item PUT $url, [Header => Value,...]
  326.  
  327. Like GET() but the method in the request is PUT.
  328.  
  329. =item POST $url, [$form_ref], [Header => Value,...]
  330.  
  331. This works mostly like GET() with POST as the method, but this function
  332. also takes a second optional array or hash reference parameter
  333. ($form_ref).  This argument can be used to pass key/value pairs for
  334. the form content.  By default we will initialize a request using the
  335. C<application/x-www-form-urlencoded> content type.  This means that
  336. you can emulate a HTML E<lt>form> POSTing like this:
  337.  
  338.   POST 'http://www.perl.org/survey.cgi',
  339.        [ name   => 'Gisle Aas',
  340.          email  => 'gisle@aas.no',
  341.          gender => 'M',
  342.          born   => '1964',
  343.          perc   => '3%',
  344.        ];
  345.  
  346. This will create a HTTP::Request object that looks like this:
  347.  
  348.   POST http://www.perl.org/survey.cgi
  349.   Content-Length: 66
  350.   Content-Type: application/x-www-form-urlencoded
  351.  
  352.   name=Gisle%20Aas&email=gisle%40aas.no&gender=M&born=1964&perc=3%25
  353.  
  354. The POST method also supports the C<multipart/form-data> content used
  355. for I<Form-based File Upload> as specified in RFC 1867.  You trigger
  356. this content format by specifying a content type of C<'form-data'> as
  357. one of the request headers.  If one of the values in the $form_ref is
  358. an array reference, then it is treated as a file part specification
  359. with the following interpretation:
  360.  
  361.   [ $file, $filename, Header => Value... ]
  362.  
  363. The first value in the array ($file) is the name of a file to open.
  364. This file will be read and its content placed in the request.  The
  365. routine will croak if the file can't be opened.  Use an C<undef> as $file
  366. value if you want to specify the content directly.  The $filename is
  367. the filename to report in the request.  If this value is undefined,
  368. then the basename of the $file will be used.  You can specify an empty
  369. string as $filename if you don't want any filename in the request.
  370.  
  371. Sending my F<~/.profile> to the survey used as example above can be
  372. achieved by this:
  373.  
  374.   POST 'http://www.perl.org/survey.cgi',
  375.        Content_Type => 'form-data',
  376.        Content      => [ name  => 'Gisle Aas',
  377.                          email => 'gisle@aas.no',
  378.                          gender => 'M',
  379.                          born   => '1964',
  380.                          init   => ["$ENV{HOME}/.profile"],
  381.                        ]
  382.  
  383. This will create a HTTP::Request object that almost looks this (the
  384. boundary and the content of your F<~/.profile> is likely to be
  385. different):
  386.  
  387.   POST http://www.perl.org/survey.cgi
  388.   Content-Length: 388
  389.   Content-Type: multipart/form-data; boundary="6G+f"
  390.  
  391.   --6G+f
  392.   Content-Disposition: form-data; name="name"
  393.   
  394.   Gisle Aas
  395.   --6G+f
  396.   Content-Disposition: form-data; name="email"
  397.   
  398.   gisle@aas.no
  399.   --6G+f
  400.   Content-Disposition: form-data; name="gender"
  401.   
  402.   M
  403.   --6G+f
  404.   Content-Disposition: form-data; name="born"
  405.   
  406.   1964
  407.   --6G+f
  408.   Content-Disposition: form-data; name="init"; filename=".profile"
  409.   Content-Type: text/plain
  410.   
  411.   PATH=/local/perl/bin:$PATH
  412.   export PATH
  413.  
  414.   --6G+f--
  415.  
  416. If you set the $DYNAMIC_FILE_UPLOAD variable (exportable) to some TRUE
  417. value, then you get back a request object with a subroutine closure as
  418. the content attribute.  This subroutine will read the content of any
  419. files on demand and return it in suitable chunks.  This allow you to
  420. upload arbitrary big files without using lots of memory.  You can even
  421. upload infinite files like F</dev/audio> if you wish; however, if
  422. the file is not a plain file, there will be no Content-Length header 
  423. defined for the request.  Not all servers (or server
  424. applications) like this.  Also, if the file(s) change in size between
  425. the time the Content-Length is calculated and the time that the last
  426. chunk is delivered, the subroutine will C<Croak>.
  427.  
  428. =back
  429.  
  430. =head1 SEE ALSO
  431.  
  432. L<HTTP::Request>, L<LWP::UserAgent>
  433.  
  434.  
  435. =head1 COPYRIGHT
  436.  
  437. Copyright 1997-2000, Gisle Aas
  438.  
  439. This library is free software; you can redistribute it and/or
  440. modify it under the same terms as Perl itself.
  441.  
  442. =cut
  443.  
  444.